const db = wx.cloud.database()
const {
  get_teacher_info
} = require('../../../Class/get_teacher_info.js');
const {
  get_class_info
} = require('../../../Class/get_class_video.js');
const teacherInfo = new get_teacher_info();
const classInfo = new get_class_info();

Page({
  data: {
    class: [],
    flag: false,
    star: false
  },

  async onLoad(options) {
    try {
      wx.showLoading({
        title: '数据通信中',
        mask: true
      })
      const result = await db.collection('panduan').get({})
      const video_info = JSON.parse(options.video_info)
      const res = await classInfo.GetClass_index();
      const { total_lesson } = res
      const lesson_map = total_lesson.reduce((map, lesson) => {
        const teacher = lesson.teacher;
        if (!map[teacher]) {
          map[teacher] = [];
        }
        map[teacher].push(lesson);
        return map;
      }, {});
      const more_class = Object.values(lesson_map).flatMap((lessons) =>
        lessons.filter((lesson, index, arr) => {
          return (
            lesson.teacher === video_info.teacher &&
            lesson.url !== video_info.url &&
            arr.findIndex((l) => l.url === lesson.url) === index
          );
        })
      );
      if (more_class.length != 0) {
        this.setData({
          flag: true
        })
      }
      this.GetBendiClass(video_info)
      this.setData({
        panduan: result.data[0].flag,
        text: video_info.text,
        video_url: video_info.url,
        teacher_name: video_info.teacher,
        teacher_img: video_info.teacher_img,
        teacher_introduce: video_info.teacher_introduce,
        more_class,video_info
      })
      wx.hideLoading()
      wx.pageScrollTo({
        scrollTop: 0
      })
      wx.showToast({
        title: '加载完成',
        icon: 'none'
      })
    } catch (err) {
      console.log('数据加载错误---', err)
      wx.showModal({
        content: '数据加载错误',
        showCancel: false
      })
    }
  },
  
  Play(e) {
    const today = new Date();
    const todayInfo = {
      year: today.getFullYear(),
      month: today.getMonth() + 1,
      day: today.getDate(),
      weekday: ["周日", "周一", "周二", "周三", "周四", "周五", "周六"][today.getDay()]
    };
    let list = wx.getStorageSync('study_day') || [];
    if (!list.some(item => item.year === todayInfo.year && item.month === todayInfo.month && item.day === todayInfo.day)) {
      list.push(todayInfo);
      wx.setStorageSync('study_day', list);
      wx.showModal({
        title: '打卡成功',
        showCancel: false
      });
    }
  },

  GoClass(e) {
    var userid = e.currentTarget.dataset.id
    this.onLoad({
      video_info: JSON.stringify(this.data.more_class[userid])
    })
  },

  Collection(e) {
    const { star, video_info } = this.data;
    const data = wx.getStorageSync('UserData') || { class: [] };
    wx.showLoading({ title: '收藏处理中' });
    if (!star) {
      data.class.push(video_info);
      wx.setStorageSync('UserData', data);
    } else {
      const index = data.class.findIndex(c => c.url === video_info.url);
      if (index !== -1) {
        data.class.splice(index, 1);
        wx.setStorageSync('UserData', data);
      }
    }
    const db = wx.cloud.database();
    const user = db.collection('user').where({
      _openid: data._openid
    }).get();
    const userData = {
      class: data.class
    };
    const updateUser = user.then(res => {
      return db.collection('user').doc(res.data[0]._id).update({
        data: userData
      });
    });
    Promise.all([user, updateUser]).then(() => {
      wx.hideLoading();
      wx.showToast({ title: '处理成功', icon: 'success' });
    }).catch(err => {
      console.error(err);
      wx.hideLoading();
      wx.showToast({ title: '失败', icon: 'none' });
    });
    this.setData({ star: !star });
  },

  async TeacherInfo() {
    wx.showLoading({
      title: '数据通信中',
      mask: true
    })
    const { total_teacherInfo } = await teacherInfo.GetTeacherInfo();
    const teacher_info = total_teacherInfo.find(teacher => teacher.name === this.data.teacher_name);
    let tabid;
    switch (teacher_info.subject) {
      case 'hanyuyan':
        tabid = 0;
        break;
      case 'xinwen':
        tabid = 1;
        break;
      case 'wangxin':
        tabid = 2;
        break;
    }
    wx.navigateTo({
      url: `/pages/teachers-team/introduce/introduce?tabid=${tabid}&teacherid=${teacher_info.id}`,
    });
    wx.hideLoading()
  },
  GetBendiClass(options){
    const user = wx.getStorageSync('UserData');
    const class_info = user.class;
    const star = class_info.some(item => item.url === options.url); 
    this.setData({ star });    
  }
})